import re

from pywinauto.application import Application
import time
import os
import openpyxl


def extract_one(mainWindow, input_txt):
    # mainWindow.Edit2.type_keys(input_txt)
    mainWindow.Edit2.set_text(input_txt)
    # mainWindow.button3.click();
    # try:
    # mainWindow.button1.click()
    # except:
    #     pass
    # time.sleep(1)
    ret = mainWindow.Edit1.get_value()
    # print(ret)
    return ret


def extract_all(mainWindow, input_file='input.txt', output_dir='out'):
    os.makedirs(output_dir, exist_ok=True)
    with open(input_file, 'r', encoding='utf8', errors='ignore') as f:
        for line in f.readlines():
            if len(line) > 3:
                input_text = line.strip()
                ret = extract_one(mainWindow, input_text)
                if '没有查询到此SS的书签' in ret:
                    continue
                out_file_name = os.path.join(output_dir, f'{input_text}.txt')
                if os.path.isfile(out_file_name):
                    continue
                with open(out_file_name, "w", encoding='utf-8') as fw:
                    fw.write(ret)
                    print(f'wrote {out_file_name}')


def batch_input_save():
    app = Application(backend='uia')
    exe_path = r'C:/Users/windows/Desktop/py-auto-input-master/._cache_书签获取软件V0505.exe'
    app.connect(path=exe_path)
    # app.window(title_re="书签获取小工具*").print_control_identifiers()
    win = app.window(title_re="书签获取小工具*")
    extract_all(win)


reg_menu = re.compile(r'(\S.+\S)\s+(\d+)\s*$')


def split_menu_line(line):
    m = reg_menu.search(line)
    if m:
        return m.group(1), m.group(2)


def txt_to_excel(txt_file_name, xlsx_file_name, template_file_name='template.xlsx'):
    '''
    转换一个txt为excel
    :param txt_file_name: txt名称
    :param xlsx_file_name: excel名称
    :param template_file_name: 模板名称
    :return:
    '''
    print(txt_file_name)
    book = openpyxl.load_workbook(template_file_name)
    sheet = book.active
    with open(txt_file_name, 'r', encoding='utf8', errors='ignore') as f:
        row_index = 4
        for line in f.readlines():
            print(line)
            result = split_menu_line(line)
            if not result:
                continue
            menu, page = result
            sheet.cell(row=row_index, column=3).value = menu
            sheet.cell(row=row_index, column=4).value = page
            sheet.cell(row=row_index, column=8).value = f'=D{row_index}+E4'
            row_index += 1
        book.save(xlsx_file_name)
        print(f'wrote to {xlsx_file_name}')


def txts_to_excels(txt_dir, xlsx_dir):
    '''
    多个txt文件转excel
    :param txt_dir: txt所在文件夹
    :param xlsx_dir: 转换的excel的文件夹
    :return:
    '''
    if not os.path.isdir(txt_dir):
        print(f'{txt_dir} not exist!')
        return
    if not os.path.isdir(xlsx_dir):
        os.makedirs(xlsx_dir, exist_ok=True)
    for txt_f in os.listdir(txt_dir):
        if not txt_f.endswith('.txt'):
            continue
        xlsx_file_name = os.path.join(xlsx_dir, txt_f.replace('.txt', '.xlsx'))
        if os.path.isfile(xlsx_file_name):
            continue
        txt_full = os.path.join(txt_dir, txt_f)
        txt_to_excel(txt_full, xlsx_file_name)


if __name__ == '__main__':
    # batch_input_save() #自动输入和提取

    # txt_to_excel(r"C:\Users\YANG.LEI\Downloads\10010032\10010032.txt",
    #              r"C:\Users\YANG.LEI\Downloads\10010032\10010032.xlsx", )
    txts_to_excels(r"C:\Users\windows\Desktop\党史系列资料",
                   r"C:\Users\windows\Desktop\党史系列资料")
